package com.inepex.graphicstests.client.govscanvasperf;

import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.user.client.Timer;
import com.inepex.graphicstests.client.misc.Globals;

public class Runner {

	private Runnable runnable;
	private int updateCount;
	private int totalGOCount;
	private long startedAt;

	private Timer timer;

	public void run(Runnable runnable){
		if(runnable == null){
			return;
		}
		if(timer != null){
			stop();
		}
		this.runnable = runnable;
		timer = new Timer() {
			@Override
			public void run() {
				doUpdate();
			}
		};
		totalGOCount = updateCount = 0;
		startedAt = System.currentTimeMillis();
		timer.scheduleRepeating(Globals.refreshRate);
		Log.debug("=================================================");
		Log.debug("Runnable started");

	}

	public void stop(){
		if(timer == null){
			return;
		}
		timer.cancel();
		long duration = System.currentTimeMillis() - startedAt;
		Log.debug("****************************************");
		Log.debug("Runnable stopped");
		Log.debug("has been running for: " + duration / 1000 + " sec");
		Log.debug("update cycles: " + updateCount + " times");
		Log.debug("total GOs shown: " + totalGOCount);
		Log.debug("average update duration: " + duration / updateCount + " ms");
		Log.debug("=================================================");
		timer = null;
	}

	void doUpdate() {
		long start = System.currentTimeMillis();
		int goCount = runnable.doUpdate();
		totalGOCount += goCount;
		updateCount++;
		if(Globals.showUpdateInfo){
			Log.debug(goCount + " GOs updated in: " + (System.currentTimeMillis() - start) + " ms");
		}
	}

}
